import {RouteLocationNormalized, RouteRecordRaw} from 'vue-router';
import {useUserStore} from '@/store';

export default function usePermission() {
  const userStore = useUserStore();
  return {
    accessRouter(route: RouteLocationNormalized | RouteRecordRaw) {
      // @ts-ignore
      if(!route || Object.keys(route.meta).length === 0){
           return true;
      }
      const perm = route.meta?.perm as  string;
      return (
          !perm ||
          !route.meta?.requiresAuth ||
          userStore.perms?.includes(perm)
      );
    },
    findFirstPermissionRoute(_routers: any, perms:string[]) {
      const cloneRouters = [..._routers];
      while (cloneRouters.length) {
        const firstElement = cloneRouters.shift();
          if (
              perms.includes(firstElement?.meta?.perm) ||
              !firstElement.meta?.requiresAuth
          )
          return { name: firstElement.name };
        if (firstElement?.children) {
          cloneRouters.push(...firstElement.children);
        }
      }
      return null;
    },

    findRouteMeta(name: string,_routers:any) {
      // console.log(name)
      // console.log(_routers)
      const cloneRouters = [..._routers];
      while (cloneRouters.length) {
        const firstElement = cloneRouters.shift();
        if (
            firstElement?.meta && name === (firstElement?.name)
        )
          return firstElement;
        if (firstElement?.children) {
          cloneRouters.push(...firstElement.children);
        }
      }
      return null;
    },



    // You can add any rules you want
  };
}
